﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using DevExpress.XtraBars;
using Excel = Microsoft.Office.Interop.Excel;

namespace QuanLyCongDan.GUI
{
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        System.Data.OleDb.OleDbCommand comm;
        bool bIsLogin = false;
        string userName;
        //private delegate void ClearListViewDelegate();
        //ClearListViewDelegate myListViewClearDelegate;

        public MainForm()
        {
            InitializeComponent();

            #region Set Window Size
            //create an object of class Rectangle (rect)
            Rectangle rect = new Rectangle();
            //rect get data from the function returning the working area of the screen
            rect = Screen.GetWorkingArea(this);
            //place our form at left
            this.Left = 0;
            //place our form at top
            this.Top = 0;
            //set the size (width and height) of our form as the size of the screen
            //working area
            this.Size = new Size(rect.Width, rect.Height); 
            #endregion

            InitializeListDonVi();
            //myListViewClearDelegate = new ClearListViewDelegate(ClearListView);
            //SetAsLogout();
        }

        private void ClearListView()
        {
            listViewDonVi.Clear();
        }

        private void InitializeListDonVi()
        {
            //listViewDonVi.Invoke(myListViewClearDelegate);
            listViewDonVi.Clear();

            try
            {
                List<DTO.DTO_DonVi> listDonVi = DAL.DAL_DonVi.GetListDonVi();
                comboBoxDonVi.DataSource = listDonVi;
                comboBoxDonVi.DisplayMember = "TenDonVi";
                comboBoxDonVi.ValueMember = "MaDonVi";
                foreach (DTO.DTO_DonVi curDonVi in listDonVi)
                {
                    listViewDonVi.Items.Add(curDonVi.TenDonVi, curDonVi.MaDonVi);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Database error");
            }
        }

        private void SetEnable(bool state)
        {
            //btnĐangKy.Enabled = state;
            btnDangNhap2.Enabled = !state;
            barbtnDangNhap.Enabled = !state;
            btnDanhSachCongDan.Enabled = state;
            btnDanhSachTaiKhoan.Enabled = state;
            btnDoiPass.Enabled = state;
            btnThemBangTay.Enabled = state;
            btnThemCDTuExcel.Enabled = state;
            btnThemCongDan.Enabled = state;
            btnThoat.Enabled = state;
            //btnTimKiemCongdan.Enabled = state;
            btnChinhSuaCongdan.Enabled = state;
            btnChinhSuaDonvi.Enabled = state;
            btnThemDonVi.Enabled = state;

            bIsLogin = state;
        }

        private void SetAsLogin()
        {
            SetEnable(true);
        }

        private void SetAsLogout()
        {
            SetEnable(false);
        }

        private void btnDangNhap_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDangNhap frm = new frmDangNhap();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                SetAsLogin();
                userName = frm.UserName;
            }
        }

        private void btnĐangKy_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDangKy frm = new frmDangKy();
            frm.ShowDialog();
        }

        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDanhsachCongdan frm = new frmDanhsachCongdan(bIsLogin);
            frm.Show();
        }

        private void barButtonItem4_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDanhsachDonVi frm = new frmDanhsachDonVi(bIsLogin);
            frm.Show();
        }

        private void btnDanhSachTaiKhoan_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDanhsachTaiKhoan frm = new frmDanhsachTaiKhoan();
            frm.Show();
        }

        private void btnThemCongDan_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmThemCongDan frm = new frmThemCongDan();
            frm.ShowDialog();
        }

        private void btnThemBangTay_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmThemCongDan frm = new frmThemCongDan();
            frm.ShowDialog();
        }

        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmThemDonVi frm = new frmThemDonVi();
            frm.ShowDialog();
            InitializeListDonVi();
            dataGridViewFoundCongDan.DataSource = null;
        }

        private void barButtonItem6_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmTimKiemCongDan frm = new frmTimKiemCongDan();
            frm.Show();
        }

        private void barButtonItem7_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmChinhsuaConDan frm = new frmChinhsuaConDan();
            frm.ShowDialog();
        }

        private void barButtonItem8_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmChinhsuaDonVi frm = new frmChinhsuaDonVi();
            frm.ShowDialog();
            InitializeListDonVi();
        }

        private void btnDoiPass_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDoiPass frm = new frmDoiPass(userName);
            frm.ShowDialog();
        }

        private void btnThemCDTuExcel_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmThemTuExcel frm = new frmThemTuExcel();
            frm.ShowDialog();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

            //Thread listDonViThread = new Thread(new ThreadStart(InitializeListDonVi));
            //listDonViThread.IsBackground = true;
            //listDonViThread.Start();
        }

        private void btnThoat_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show("Bạn muốn thoát?", "Logout", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                SetAsLogout();
            }
        }

        private void btnAboutCauHinh_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmCauHinh frm = new frmCauHinh();
            frm.ShowDialog();
        }

        private void barButtonItem6_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            frmBanQuyen frm = new frmBanQuyen();
            frm.ShowDialog();
        }

        private void barButtonItem5_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            AboutTreViet frm = new AboutTreViet();
            frm.ShowDialog();
        }

        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {

        }

        private void listViewDonVi_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewDonVi.SelectedItems.Count == 0)
                return;
            dataGridViewFoundCongDan.DataSource = null;

            ListViewItem curListViewDonVi = listViewDonVi.SelectedItems[0];
            DTO.DTO_CongDan congDanSearchCondition = new QuanLyCongDan.DTO.DTO_CongDan();
            comm = new System.Data.OleDb.OleDbCommand();
            List<DTO.DTO_Field> listFieldDonVi = DAL.DAL_Field.GetListFieldDonVi(curListViewDonVi.ImageKey);
            
            string fieldStr = "MaCD, MaDonVi,";
            foreach (DTO.DTO_Field curField in listFieldDonVi)
            {
                fieldStr += curField.TenField + ",";
            }
            fieldStr = fieldStr.Substring(0, fieldStr.Length - 1);

            congDanSearchCondition.DonVi = curListViewDonVi.ImageKey;
            try
            {
                comm = DAL.DAL_CongDan.OleDBCommandSearchCongDan(congDanSearchCondition);
                comm.CommandText = comm.CommandText.Replace("*", fieldStr);

                DataSet ds = DAL.DAL_CongDan.GetCongDanTable(comm);
                dataGridViewFoundCongDan.DataSource = ds.Tables[0];
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void simpleButtonUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)dataGridViewFoundCongDan.DataSource;
                DAL.DAL_CongDan.UpdateCongDanTable(comm, dt.DataSet);
                MessageBox.Show("Hoàn tất");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void simpleButtonExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Chọn tên File excel sẽ lưu";
            saveFileDialog.Filter = "Excel 2003|*.xls";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportData2Excel(saveFileDialog.FileName);
            }
        }

        private void ExportData2Excel(string filePath)
        {
            ListViewItem curListViewDonVi = listViewDonVi.SelectedItems[0];
            List<DTO.DTO_Field> listFieldDonVi = DAL.DAL_Field.GetListFieldDonVi(curListViewDonVi.ImageKey);

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range; 
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(filePath, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
           

            
            int DongDau = DAL.DAL_DonVi.GetTemplateDonViDongDau(curListViewDonVi.ImageKey);

            DataTable dt = (DataTable)dataGridViewFoundCongDan.DataSource;
            int count = 0;
            
            foreach (DataRow curRow in dt.Rows)
            {
                range = xlWorkSheet.UsedRange;
                range = (Excel.Range)range.Cells[DongDau + count, 1];
                range = range.EntireRow;
                
                range.Insert(Excel.XlInsertShiftDirection.xlShiftDown, misValue);
                
                foreach (DTO.DTO_Field curField in listFieldDonVi)
                {
                    xlWorkSheet.Cells[DongDau + count, curField.Value] = curRow[curField.TenField];
                }
                count++;
			}

            xlWorkBook.SaveAs(
                filePath,
                Excel.XlFileFormat.xlWorkbookNormal,
                misValue,
                misValue,
                misValue,
                misValue,
                Excel.XlSaveAsAccessMode.xlExclusive,
                misValue,
                misValue,
                misValue,
                misValue,
                misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            MessageBox.Show("Hoàn tất");
        }

        private void comboBoxEditDonVi_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            Int32 selectedCellCount = dataGridViewFoundCongDan.GetCellCount(DataGridViewElementStates.Selected);
            if (selectedCellCount > 0)
            {
                if (dataGridViewFoundCongDan.Columns[dataGridViewFoundCongDan.SelectedCells[0].ColumnIndex].Name == "MaDonVi")
                {
                    foreach (DataGridViewCell curCell in dataGridViewFoundCongDan.SelectedCells)
                    {
                        curCell.Value = ((DTO.DTO_DonVi)comboBoxDonVi.SelectedItem).MaDonVi;
                    } 
                }
            }
            
        }

    }
}
